package com.proxy.server.backend.bio;

import com.proxy.common.packet.BinaryPacket;
import com.proxy.server.backend.Trigger;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liufish on 16/12/22.
 */
public class SyncReceiver {

    private Trigger trigger;

    public void receive(BioBackendConnection connection){
        BinaryPacket header = connection.receive();
        if(header.body[0] == (byte)0x00){
            this.triggerSuccess(header);
            return;
        }

        if(header.body[0] == (byte)0xff){
            this.triggerError(header);
            return;
        }
        //bin.body[0] == (byte) 251文件,暂时不支持
        //保存head

        //field field_eof
        List<BinaryPacket> fields = new ArrayList<BinaryPacket>();
        for (;;){
            BinaryPacket fieldPacket  = connection.receive();
            // error
            if(fieldPacket.body[0] == (byte) 0xff){
                this.triggerError(fieldPacket);
                return;
            }
            //FIELD_EOF
            if(fieldPacket.body[0] == (byte)0xfe){
                //这里一起输出 head fields eof
                this.triggerHeadFieldsEof(header, fields, fieldPacket);
                break;
            }
            fields.add(fieldPacket);
        }

        //处理RowData数据
        for(;;){
            BinaryPacket rowPacket = connection.receive();
            //error
            if(rowPacket.body[0] == (byte)0xff){
                this.triggerError(rowPacket);
                return;
            }
            //last eof
            if(rowPacket.body[0]== (byte)0xfe){
                //输出bin/last_eof
                this.triggerRowsEof(rowPacket);
                break;
            }
            //输出bin/row不再缓存
            this.triggerRow(rowPacket);
        }
    }



    void triggerSuccess(BinaryPacket bin){
        if(trigger != null)
        this.trigger.onSuccess(bin);
    }

    void triggerError(BinaryPacket bin){
        if(trigger != null)
        this.trigger.onError(bin);
    }

    void triggerHeadFieldsEof(BinaryPacket head, List<BinaryPacket> fields,BinaryPacket eof){
        if(trigger != null)
        this.trigger.onHeadFieldsEof(head, fields, eof);
    }

    void triggerRow(BinaryPacket row){
        if(trigger != null)
        this.trigger.onRow(row);
    }

    void triggerRowsEof(BinaryPacket bin){
        if(trigger != null)
        this.trigger.onRowsEof(bin);
    }

    public void setTrigger(Trigger trigger){
        this.trigger =  trigger;

    }
}
